package com.hakgc.rent.web.filter;

import com.hakgc.rent.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 要求rent目录下的所有请求都必须登录后再访问
 * @author Xing.Jiejian
 * @date 2020/11/17
 */
//@WebFilter(filterName = "RentFilter",urlPatterns = "/rent/*")
public class RentFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 从Session中获取当前登录用户
        HttpSession session = ((HttpServletRequest)req).getSession();
        User user = (User) session.getAttribute("currentUser");
        if (user != null) {
            // 如果有用户则继续执行相关请求
            chain.doFilter(req, resp);
        }else{
            // 如果没有用户，则给与提示，并跳转到登录页
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.println("<script>");
            out.println("alert('登录以后才可以访问');");
            out.println("parent.location.href='"+((HttpServletRequest) req).getContextPath()+"/login';");
            out.println("</script>");
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
